package com.zhuxin.events;

import com.dbHelper.DbTemplate;
import com.google.gson.Gson;
import com.soecode.wxtools.api.IService;
import com.soecode.wxtools.bean.WxQrcode;
import com.soecode.wxtools.bean.WxXmlMessage;
import com.soecode.wxtools.bean.WxXmlOutMessage;
import com.soecode.wxtools.bean.WxXmlOutNewsMessage;
import com.soecode.wxtools.bean.result.QrCodeResult;
import com.soecode.wxtools.exception.WxErrorException;
import com.zhuxin.common.UtilTools;
import com.zhuxin.medical.model.po.CommAppLog;
import com.zhuxin.medical.mvc.controller.WxMsg;
import org.apache.commons.lang3.ArrayUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;

import java.math.BigDecimal;
import java.sql.*;
import java.util.*;
import java.util.Date;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * Created by lzb on 2018/11/16.
 */
public abstract class BaseHandler {

    @Autowired
    protected DbTemplate mysqlDao;

    @Autowired
    protected DbTemplate oracleDao;


    @Value("${wx.domainName.test}")
    protected String domainName;//域名


    public Object checkUserStatus(WxXmlMessage wxMessage, Map<String, Object> context, IService iService){
//        Map<String,String> param=new HashMap<>(10);
        final String[] rsmsg = {null};
        CommAppLog log=null;
        switch (WxMsg.curruser.get().getStatus().intValue()) {
            case 0:
                rsmsg[0] ="请输入要作废的方案ID，多个请用分隔符分隔开.";
                WxMsg.curruser.get().setStatus(1);
                WxMsg.curruser.get().setStatustime(new Date());
                this.mysqlDao.updateSub(WxMsg.curruser.get(), ArrayUtils.toArray("status","Statustime"),true);
                break;
            case 1:
                if(UtilTools.isNullOrBlank(wxMessage.getContent())){
                    rsmsg[0] ="请输入要作废的方案ID，多个请用分隔符分隔开.";
                    break;
                }
                List<Long> pids=this.matchPlanids(wxMessage.getContent());
                Map<Long,String> plans=new HashMap<>(pids.size());
                String joinpids= StringUtils.join(pids.toArray(),",");
//                    rsmsg="您需要作废的方案为:\n";
                StringBuffer sb=new StringBuffer("您需要作废的方案为:\n");
                pids.forEach(id->{
                    List<Map<String, Object>> maps = this.oracleDao.queryForList("select YJPLANID,YJPLANNAME from CO_RU_PLAN where YJPLANID = ? ", new Object[]{id});
                    if(!maps.isEmpty()){
                        plans.put(((BigDecimal)maps.get(0).get("YJPLANID")).longValue(),maps.get(0).get("YJPLANNAME").toString());
                    }else{
                        rsmsg[0] =id+"方案非生效方案!禁止发起作废请求.";
                    }
                });
                if(rsmsg[0]!=null)break;
                plans.forEach((k,v)->{
                    sb.append(k).append(",").append(v).append("\n");
                });
//                param.put("uuid", UtilTools.getUUID());
//                param.put("ids",joinpids);
//                param.put("inf",new Gson().toJson(plans));
                log=new CommAppLog();
                log.setRecid(UtilTools.getUUID());
                log.setPlanids(joinpids);
                log.setAppletime(new Date());
                log.setPlaninf(new Gson().toJson(plans));
                log.setOper(WxMsg.curruser.get().getUsercode());
                log.setOperid(WxMsg.curruser.get().getOpenid());
                log.setOpername(WxMsg.curruser.get().getUsername());
                this.mysqlDao.save(log);

                sb.append("\n").append("请说明您要作废以上"+plans.size()+"个方案的原因。如无，请直接回复 [确定] 开始送给俞姐姐微信审批.").append("\n");
                sb.append("5分钟内无回复，则放弃请求.");
                WxMsg.curruser.get().setStatus(2);
                WxMsg.curruser.get().setStatustime(new Date());
                WxMsg.curruser.get().setParam(log.getRecid());
                this.mysqlDao.updateSub(WxMsg.curruser.get(), ArrayUtils.toArray("status","Statustime","param"),true);
                rsmsg[0] =sb.toString();
                break;
            case 2:
                String reason=wxMessage.getContent();
                if(reason==null){
                    rsmsg[0] ="请回复方案作废理由.取消作废，请回复取消.";
                    break;
                }
                if(reason.equals("取消")){
                    WxMsg.curruser.get().setStatus(0);
                    WxMsg.curruser.get().setStatustime(new Date());
                    WxMsg.curruser.get().setParam(null);
                    this.mysqlDao.updateSub(WxMsg.curruser.get(),ArrayUtils.toArray("status","Statustime","param"),true);
                    log=new CommAppLog();
                    log.setRecid(WxMsg.curruser.get().getParam());
                    log.setReason("用户取消");
                    log.setStatus(998L);
                    this.mysqlDao.updateSub(log,ArrayUtils.toArray("reason","status"),true);
                    rsmsg[0] ="取消成功.";
                    break;
                }
                if("确定".equals(reason)){
                    reason="无理由.";
                }
//                param=new Gson().fromJson(WxMsg.curruser.get().getParam(),Map.class);
//                param.put("reason",reason);

                log=new CommAppLog();
                log.setRecid(WxMsg.curruser.get().getParam());
                log=this.mysqlDao.queryVoByKey(log);
                log.setReason(reason);
                log.setStatus(1L);
                this.mysqlDao.updateSub(log,ArrayUtils.toArray("reason","status"),true);
                //生成二维码
                WxQrcode code = new WxQrcode();
                code.setAction_name("QR_STR_SCENE");
                code.setAction_info(new WxQrcode.WxQrActionInfo(new WxQrcode.WxQrActionInfo.WxScene(log.getRecid())));
                code.setExpire_seconds(86400*5);//有效期5天
                try {
                    QrCodeResult result = iService.createQrCode(code);
                    String picurl=iService.getShortUrl("https://mp.weixin.qq.com/cgi-bin/showqrcode?ticket="+result.getTicket());
                    WxXmlOutNewsMessage.Item item=new WxXmlOutNewsMessage.Item();
                    item.setTitle("作废审批二维码");
                    item.setDescription("作废请求会直接发给俞姐姐微信审核，如果确实等不及，也可以将上面二维码发到群上让各位有权限的大神审核。");
                    item.setUrl(picurl);
                    item.setPicUrl(picurl);
                    WxMsg.curruser.get().setStatus(3);
                    WxMsg.curruser.get().setStatustime(new Date());
                    this.mysqlDao.updateSub(WxMsg.curruser.get(), ArrayUtils.toArray("status","Statustime"),true);
                    return WxXmlOutMessage.NEWS().addArticle(item).toUser(wxMessage.getFromUserName()).fromUser(wxMessage.getToUserName()).build();
                } catch (WxErrorException e) {
                    e.printStackTrace();
                }

                break;
            case 3:
                rsmsg[0] ="存在待审核的作废方案请求,无法发起新的审批.";
                break;
        }
        return rsmsg[0];
    }

    private List<Long> matchPlanids(String ctx){
        List<Long> pids=new ArrayList<>(20);
        Pattern pt=Pattern.compile("[0-9]+");
        Matcher matcher = pt.matcher(ctx);
        while(matcher.find()){
            pids.add(Long.valueOf(matcher.group()));
        }
        return pids;
    }
}
